package com.levi.transaction;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * 消息的消费者
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        //1.创建消费者，指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
        //2.指定nameserv地址
        consumer.setNamesrvAddr("192.168.177.129:9876");
        //3.订阅topic和tag
        consumer.subscribe("TransacTion_Topic","*");
        // FIXME 设置消费类型 广播模式和负载均衡模式，默认是负载均衡模式
//        consumer.setMessageModel(MessageModel.BROADCASTING);
//        consumer.setMessageModel(MessageModel.CLUSTERING);
        //4.设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                //发送的消息存放在msgs的body中，以byte数组形式
                for (MessageExt message:msgs){
                    System.out.println("消费的消息内容: "+new String(message.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //5.开启消费者
        consumer.start();

    }
}
